<script setup>
import { onMounted, ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAssistantStore } from '@/stores/assistant'
import { useChannelStore } from '@/stores/channels'
import { useAuthStore } from '@/stores/auth'
import { getStorageUrl, setDocumentText } from '@/utils/utils'
import { useConfigStore } from '@/stores/config'
import chatApi from '@/apis/chat'

import ChatBox from '@/components/chat/ChatBox.vue'

const route = useRoute()
const router = useRouter()

const assistantStore = useAssistantStore()
const channelStore = useChannelStore()
const authStore = useAuthStore()
const configStore = useConfigStore()

const assistantId = computed(() => parseInt(route.params?.id || 0))
const assistant = ref({})
const chatInfo = computed(() => ({
  title: assistant.value?.name,
  icon: assistant.value?.icon,
  favorite: assistant.value?.favorite,
}))

const role = computed(() => {
  return {
    user: { avatar: authStore.getAvatar() },
    assistant: { avatar: getStorageUrl(assistant.value?.icon || configStore.get('chat.avatar')) },
  }
})

const favorite = () => {
  authStore.authOrLogin(
    async () => {
      await chatApi.role.favorite.toggle(assistant.value)
      assistant.value.favorite = !assistant.value.favorite
      ElMessage.success(visrole.value.favorite ? '已收藏' : '已取消')
    },
    { router, options: { confirm: true, redirect: route.fullPath } }
  )
}

const loadAssistant = async (id) => {
  assistant.value = (await chatApi.role.read(id, 'assistant')).data
  assistantStore.setActive(assistant.value)
  setDocumentText(assistant.value.name)
}

onMounted(async () => {
  await channelStore.init()
  await loadAssistant(assistantId.value)
})

watch(assistantId, async (newId) => {
  await loadAssistant(newId)
})
</script>

<template>
  <div class="flex flex-col relative h-full w-full">
    <ChatBox
      show-clear-btn
      show-favorite-btn
      :display-styles="['list']"
      object-type="assistant"
      :object-id="assistantId"
      :channels="channelStore.data"
      :channel="channelStore.active"
      :role="role"
      :chat-info="chatInfo"
      :welcome-text="assistant?.welcome"
      :example-text="assistant?.questions"
      :prompt-placeholder="assistant?.placeholder"
      @switch-channel="channelStore.switch"
      @favorite-chat="favorite"
    >
    </ChatBox>
  </div>
</template>
